﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Dm;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Net.Configuration;
using Net.IService;
using Net.Model.Entities.Enterprises;
using Net.Model.FromBody;
using Net.Model.ViewModels.Licenses;
using Net.Model.ViewModels.UI;
using Net.Service;
using Net.Util.Extensions;
using WebApi.Infrastructure;

namespace WebApi.Controllers.System
{

    [Route("Api/[controller]/[action]")]
    [RequiredErrorForAdmin]
    public class LicenseController : ControllerBase
    {
        //private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILicenseService _licenseService;
        public LicenseController(ILicenseService licenseService)
        {
            //this._httpContextAccessor = httpContextAccessor;
            this._licenseService = licenseService;
        }


        [HttpPost]
        public async Task<WebApiCallBack> GetLicense([FromBody]FMLicense fMLicense)
        {
            //FMLicense fMLicense = ConvertObjectExtensions.ConvertObjectByJson<FMLicense>(Request.Headers["fm"].ToString());
            var result = new WebApiCallBack();
            if (fMLicense == null)
            {
                result.code = GlobalStatusCodes.Status400BadRequest;
                result.msg = "实体参数为空";
                return result;
            }
            else
            {
                #region # 验证
                if (string.IsNullOrEmpty(fMLicense.enterpriseName))
                {
                    result.code = GlobalStatusCodes.Status400BadRequest;
                    result.msg = "实体参数为空";
                    result.otherData = fMLicense;
                    return result;
                }
                if (string.IsNullOrEmpty(fMLicense.uniqueCode))
                {
                    result.code = GlobalStatusCodes.Status400BadRequest;
                    result.msg = "机器唯一码不可为空！";
                    result.otherData = fMLicense;
                    return result;
                }
                #endregion

                if (fMLicense.isExistLicense)
                {
                    //byte[] b = SerializeExtensions.Serialize(fMLicense.EnterpriseName);
                    ////加密后的License
                    //fMLicense.EnterpriseName = LicenseExtensions.Encrypt(LicenseExtensions.ToBinaryString(b));

                    //解析企业名称
                    byte[] a = Convert.FromBase64String(LicenseExtensions.Decrypt(fMLicense.enterpriseName));
                    fMLicense.enterpriseName = SerializeExtensions.Deserialize<string>(a);
                }             
            }

            #region
            //获取License
            byte[] bytes = SerializeExtensions.Serialize(fMLicense);
            string license = LicenseExtensions.ToBinaryString(bytes);
            //加密后的License，需要存入库中
            string encryptedLicense = LicenseExtensions.Encrypt(license);
            #endregion

            //业务逻辑
            AppProductLine appProductLine = null;
            var licenseDtos = await _licenseService.QueryAppLicensesByEnterpriseName(fMLicense.enterpriseName);
            if (licenseDtos != null && licenseDtos.Count > 0)
            {
                long[] LicenseIds = licenseDtos.Select(x => (long)x.LicenseId).ToArray();
                var productLines = await _licenseService.QueryProductLinesByLicenseIds(LicenseIds);
                if (productLines == null || productLines.Count == 0) //没有任何产线，首次新增产线
                {
                    //生成授权码，新增一条产线，下次该客户端登录只需要验证授权码是否存在，并且在授权期限内即可登录系统
                    LicenseDto licenseDto = licenseDtos[0];
                    appProductLine = new AppProductLine()
                    {
                        EnterpriseId = Convert.ToInt64(licenseDto.EnterpriseId),
                        ProductLineName = "产线1",
                        PLMark = fMLicense.uniqueCode,
                        LicenseId = Convert.ToInt64(licenseDto.LicenseId),
                        Yields = 0,
                        LicenseCode = encryptedLicense,
                        IsActive = true,
                        IsDeleted = false,
                        CreationTime = DateTime.Now,
                        CreatorUserId = 0,
                    };

                    var data = await _licenseService.AddProductLine(appProductLine);
                    result.code = (data != null && licenseDto.LicenseEndDateUtc > DateTime.UtcNow) ? GlobalStatusCodes.Status200Ok : GlobalStatusCodes.Status401Unauthorized;
                    result.msg = result.code == 200 ? "授权成功" : "授权失败！";
                    result.otherData = fMLicense;
                    result.data = new { LicenseCode = LicenseExtensions.Encrypt(LicenseExtensions.ToBinaryString(SerializeExtensions.Serialize(fMLicense.enterpriseName))) };
                }
                else
                {
                    //验证授权码是否存在，如果存在则回传授权码，客户端验证正确后，直接登录系统
                    var singleProductLine = productLines.SingleOrDefault(x => x.PLMark == fMLicense.uniqueCode);
                    if (singleProductLine != null)
                    {
                        var licenseDto = licenseDtos.FirstOrDefault(x => x.LicenseId == singleProductLine.LicenseId);
                        result.code = (licenseDto != null && licenseDto.LicenseEndDateUtc > DateTime.UtcNow) ? GlobalStatusCodes.Status200Ok : GlobalStatusCodes.Status401Unauthorized;
                        result.msg = result.code == 200 ? "授权成功！" : "授权失败！";
                        result.otherData = fMLicense;
                        result.data = new { LicenseCode = LicenseExtensions.Encrypt(LicenseExtensions.ToBinaryString(SerializeExtensions.Serialize(fMLicense.enterpriseName))) };
                    }
                    else 
                    {                       
                        long[] ids = productLines.Select(t => t.LicenseId).ToArray();
                        var list = licenseDtos.Where(t=>!ids.Contains(t.LicenseId)).OrderBy(t => t.LicenseId).ToArray();

                        if (list.Count() > 0)
                        {
                            LicenseDto licenseDto = list[0];
                            appProductLine = new AppProductLine()
                            {
                                EnterpriseId = Convert.ToInt64(licenseDto.EnterpriseId),
                                ProductLineName = "产线" + (productLines.Count + 1),
                                PLMark = fMLicense.uniqueCode,
                                LicenseId = Convert.ToInt64(licenseDto.LicenseId),
                                Yields = 0,
                                LicenseCode = encryptedLicense,
                                IsActive = true,
                                IsDeleted = false,
                                CreationTime = DateTime.Now,
                                CreatorUserId = 0,
                            };

                            var data = await _licenseService.AddProductLine(appProductLine);
                            result.code = (data != null && licenseDto.LicenseEndDateUtc > DateTime.UtcNow) ? GlobalStatusCodes.Status200Ok : GlobalStatusCodes.Status401Unauthorized;
                            result.msg = result.code == 200 ? "授权成功" : "授权失败！";
                            result.otherData = fMLicense;
                            result.data = new { LicenseCode = LicenseExtensions.Encrypt(LicenseExtensions.ToBinaryString(SerializeExtensions.Serialize(fMLicense.enterpriseName))) };
                        }
                        else
                        {
                            result.code = GlobalStatusCodes.Status401Unauthorized;
                            result.otherData = fMLicense;
                            result.msg = result.code == 200 ? "授权成功" : "授权失败，产线数量超过企业已授权license数量！";
                        }                     
                    }
                }
            }
            else
            {
                result.code = GlobalStatusCodes.Status401Unauthorized;
                result.otherData = fMLicense;
                result.msg = "不存在授权信息！";
            }
            return result;
        }

        [HttpPost]
        public async Task<WebApiCallBack> Test([FromBody] Test fTest)
        {
            await Task.Delay(1000);
            return new WebApiCallBack() { code = 200, msg = "测试成功！" };
        }


    }
}
